﻿using Application.Adapter;
using Application.Common.Extensions;
using Application.Common.Interface;
using Domain;
using Domain.Enums;
using Domain.Models;
using Domain.Models.Cmd;
using MediatR;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Sockets;

namespace Application.App.Command
{
    public class OutOfWineCommand : IRequest<Result>
    {
        /// <summary>
        /// 设备id
        /// </summary>
        public string DeviceId { get; set; }

        /// <summary>
        /// 通道号
        /// </summary>
        public int ChannelNum { get; set; }
        /// <summary>
        /// 出酒量
        /// </summary>
        public int OutOfWineNum { get; set; }
    }
    public class OutOfWineCommandHandle : IRequestHandler<OutOfWineCommand,Result>
    {
        private readonly ITcpService tcpService;
        private readonly ICustomTcpClient customTcpClient;
        public OutOfWineCommandHandle(ITcpService tcpService, ICustomTcpClient customTcpClient)
        {
            this.tcpService = tcpService;
            this.customTcpClient = customTcpClient;
        }
        public async Task<Result> Handle(OutOfWineCommand request, CancellationToken cancellationToken)
        {

            if (request.OutOfWineNum > 20000)
            {
                return Result.FromError("每次出酒量最大为20000ml");
            }

            //找到设备id对应的socketId索引
            //Consts.ScoketIDToDeviceId.TryGetKey(request.DeviceId, out var socketId);

            var buffer = new List<byte> { Consts.StartByte, 0x0C };
            buffer.AddRange(request.DeviceId.HexStringToByteArray());
            buffer.Add(((int)DataType.出酒命令下).ToByte());
            buffer.Add(request.ChannelNum.ToByte());
            buffer.AddRange(request.OutOfWineNum.ToTwoByte());
            buffer.Add(buffer.GetVaildByteCode());
            buffer.Add(Consts.EndByte);
            await Console.Out.WriteLineAsync(Convert.ToHexString(buffer.ToArray()));
            try
            {
                customTcpClient.Send(buffer.ToArray());

                return Result.Success;
                
            }
             catch (Exception ex)
            {
                return new Result(ResultCode.Error, ex.Message);
            }
        }
    }
}
